﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using System.IO;

namespace AAA.Base.Util
{
    public class ExcelHelper
    {
        public static void DataGridViewToExcel(DataGridView dgv)
        {
            #region 
            //驗證可操作性
            //申明保存對話方塊
            SaveFileDialog dlg = new SaveFileDialog();
            //默然文件尾碼
            dlg.DefaultExt = "xls ";
            //文件尾碼列表
            dlg.Filter = "EXCEL文件(*.XLS)|*.xls ";
            //默然路徑是系統當前路徑
            dlg.InitialDirectory = Directory.GetCurrentDirectory();
            //打開保存對話方塊
            if (dlg.ShowDialog() == DialogResult.Cancel) 
                return;
            //返回檔路徑
            string fileNameString = dlg.FileName;
            //驗證strFileName是否為空或值無效
            if (fileNameString.Trim() == " ")
            { 
                return; 
            }
            //定義表格內資料的行數和列數
            int rowscount = dgv.Rows.Count;
            int colscount = dgv.Columns.Count;
            //行數必須大於0
            if (rowscount <= 0)
            {
                MessageBox.Show("沒有資料可供保存 ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            //列數必須大於0
            if (colscount <= 0)
            {
                MessageBox.Show("沒有資料可供保存 ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            //行數不可以大於65536
            if (rowscount > 65536)
            {
                MessageBox.Show("資料記錄數太多(最多不能超過65536條)，不能保存 ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            //列數不可以大於255
            if (colscount > 255)
            {
                MessageBox.Show("資料記錄行數太多，不能保存 ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            //驗證以fileNameString命名的檔是否存在，如果存在刪除它
            FileInfo file = new FileInfo(fileNameString);
            if (file.Exists)
            {
                try
                {
                    file.Delete();
                }
                catch (Exception error)
                {
                    MessageBox.Show(error.Message, "刪除失敗 ", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }
            #endregion

            Microsoft.Office.Interop.Excel.Application objExcel = null;
            Microsoft.Office.Interop.Excel.Workbook objWorkbook = null;
            Microsoft.Office.Interop.Excel.Worksheet objsheet = null;
            try
            {
                //申明對象
                objExcel = new Microsoft.Office.Interop.Excel.Application();
                objWorkbook = objExcel.Workbooks.Add(Missing.Value);
                objsheet = (Microsoft.Office.Interop.Excel.Worksheet)objWorkbook.ActiveSheet;
                //設置EXCEL不可見
                objExcel.Visible = false;
                //向Excel中寫入表格的表頭
                int displayColumnsCount = 1;
                for (int i = 0; i <= dgv.ColumnCount - 1; i++ )
                {
                    if (dgv.Columns[i].Visible == true)
                    {
                        objExcel.Cells[1, displayColumnsCount] = dgv.Columns[i].HeaderText.Trim();
                        displayColumnsCount++;
                    }
                }
                //設置進度條
                //tempProgressBar.Refresh();
                //tempProgressBar.Visible = true;
                //tempProgressBar.Minimum=1;
                //tempProgressBar.Maximum=dgv.RowCount;
                //tempProgressBar.Step=1;
                //向Excel中逐行逐列寫入表格中的資料
                for (int row = 0; row <= dgv.RowCount - 1; row++ )
                {
                    //tempProgressBar.PerformStep();
                    displayColumnsCount = 1;
                    for (int col = 0; col < colscount; col++ )
                    {
                        if (dgv.Columns[col].Visible == true)
                        {
                            try
                            {
                                objExcel.Cells[row + 2, displayColumnsCount] = dgv.Rows[row].Cells[col].Value.ToString().Trim();
                                displayColumnsCount++;
                            }
                            catch (Exception)
                            {
                            }
                        }
                    }
                }
                //隱藏進度條
                //tempProgressBar.Visible = false;
                //保存檔
                objWorkbook.SaveAs(fileNameString, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
                Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, Missing.Value, Missing.Value, Missing.Value,
                Missing.Value, Missing.Value);
            }
            catch (Exception error)
            {
                MessageBox.Show(error.Message, "警告 ", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            finally
            {
                //關閉Excel應用
                if (objWorkbook != null) 
                    objWorkbook.Close(Missing.Value, Missing.Value, Missing.Value);
                if (objExcel.Workbooks != null) 
                    objExcel.Workbooks.Close();
                if (objExcel != null) 
                    objExcel.Quit();
                objsheet = null;
                objWorkbook = null;
                objExcel = null;
            }
            MessageBox.Show(fileNameString + "\n\n匯出完畢! ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}
